<template>
    <div>
        <div style="margin: 10px 5px">
            <span>节点ID</span>
            <el-input v-model="formInfo.id" style="width: 50%; margin-left: 25px" disabled></el-input>
        </div>
        <div style="margin: 10px 5px">
            <span>节点名称</span>
            <el-input v-model="formInfo.name" style="width: 50%; margin-left: 10px"></el-input>
        </div>
        <div v-for="(val, index) in formData" :key="index">
            <el-card>
                <div class="itemTitle">
                    <div>
                        <span>{{ val.title }}</span><span>{{ index + 1 }}</span>
                    </div>
                    <div>
                        <i class="el-icon-delete-solid delete" @click="deleteItem(formData, index)"></i>
                    </div>
                </div>
                <div v-for="(item, index) in val.data" :key="index">
                    <div style="" class="formItem">
                        <el-select v-model="item.value1" placeholder="请选择" clearable
                            @change="(e) => firstChange(e, item, val)" style="width: 100px">
                            <el-option v-for="res in typeOptions" :key="res.fieldKey" :label="res.fieldName"
                                :value="res.fieldKey">
                            </el-option>
                        </el-select>

                        <el-select v-model="item.value2" placeholder="请选择" clearable
                            @change="(e) => secendChange(e, item, val)" style="
                                margin-left: 10px;
                                margin-right: 10px;
                                width: 80px;
                            " :disabled="item.value2_disabled">
                            <el-option v-for="item in item.typeOptions2 || []" :key="item.dictValue"
                                :label="item.dictLabel" :value="item.dictValue">
                            </el-option>
                        </el-select>

                        <el-input-number style="flex: 1" v-if="item.fieldType == 1" v-model="item.value3"
                            placeholder="请输入内容" :min="0" clearable controls-position="right"></el-input-number>
                        <el-select v-else v-model="item.value3" placeholder="请选择" clearable style="flex: 1" :disabled="item.status3">
                            <el-option v-for="item in item.typeOptions3 || []" :key="item.dictValue"
                                :label="item.dictLabel" :value="item.dictValue">
                            </el-option>
                        </el-select>
                        <i class="el-icon-delete-solid delete" @click="deleteItem(val.data, index)"></i>
                    </div>
                    <div><el-tag v-if="val.data.length > 1">or</el-tag></div>
                </div>
                <div style="text-align: center; margin-top: 10px">
                    <el-button type="primary" icon="el-icon-plus" @click="addField(val)">增加字段</el-button>
                </div>
            </el-card>
            <el-tag type="warning" v-if="formData.length > 1">and</el-tag>
        </div>
        <div style="text-align: center; margin-top: 10px">
            <el-button type="primary" icon="el-icon-plus" @click="addCondition()">增加条件</el-button>
        </div>
        <!-- <div style="text-align: right;margin-top:10px"><el-button type="primary" @click="save()">保存</el-button></div> -->
    </div>
</template>

<script>
import mixinPanel from "../../common/mixinPanel";
import mixinExecutionListener from "../../common/mixinExecutionListener";
import { commonParse } from "../../common/parseElement";
import { getFormDate, ApproveList,getLessorList } from "@/api/flowable/model";
import { StrUtil } from "@/utils/StrUtil";
import { Base64 } from "js-base64";
export default {
    mixins: [mixinPanel, mixinExecutionListener],
    data() {
        return {
            name: "",
            formData: [
                // {
                //     title: "条件",
                //     id: "1",
                //     data: [
                //         {
                //             id: "1",
                //             name: "条件",
                //             type: "",
                //             type1: "",
                //             type2: "",
                //             condition: "",
                //             value: "",
                //             input: "=",
                //             inputValue: "",
                //             state1: true,
                //             state2: true,
                //         },
                //     ],
                // },
            ],
            formInfo: {
                id: "",
                name: "",
                value: "",
            },

            typeOptions: [],
            typeOptions1: [],
            typeOptions3: [],
            typeOptions3List: [],
            fieldType: [],
        };
    },
    props: {
        config: {
            type: Array,
            required: true,
        },
        // modeler: {
        //     required: false,
        // },
    },
    computed: {},
    watch: {
        formData: {
            deep: true,
            handler(val) {
                this.formData = val;
                // this.$set(this.formInfo, 'value', Base64.encode(val))
                let a = Base64.encode(JSON.stringify(val));
                // let b = Base64.decode(a);
                delete this.element.businessObject[`value`];
                this.updateProperties({ "flowable:value": a });
                if (val?.length > 0) {
                    let str = "";
                    val.map((e, i) => {
                        if (e.data?.length > 0) {
                            str += `(${e.data
                                .map((item) => {
                                    return `${item.value1 ?? ""}${item.value2 ?? ""
                                        }${Number.isFinite(item.value3)
                                            ? item.value3
                                            : '"' + item.value3 + '"'
                                        }`;
                                })
                                .join("||")})${i == val.length - 1 ? "" : " && "
                                }`;
                        }
                    });
                    if (str) {
                        // console.log(str);
                        const newCondition = this.modeler
                            .get("moddle")
                            .create("bpmn:FormalExpression", {
                                body: `\$\{${str}\}`,
                            });

                        this.updateProperties({
                            conditionExpression: newCondition,
                        });
                    }
                }
            },
        },
        "formInfo.id": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:id": val });
            } else {
                // 删除xml中已选择表单信息
                delete this.element.businessObject[`id`];
            }
        }, // id
        "formInfo.name": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:name": val });
            } else {
                // 删除xml中已选择表单信息
                delete this.element.businessObject[`name`];
            }
        }, // 名称
    },
    async created() {
        await this.getApproveList();
        // this.getDicts("field_type").then((res) => {
        //     res.data.map((res) => {
        //         res.label = res.dictLabel;
        //         res.value = res.dictValue;
        //     });
        //     this.fieldType = res.data;
        // });
        this.getFormList();
        let cache = commonParse(this.element);
        this.formData = cache.value
            ? JSON.parse(Base64.decode(cache.value))
            : [];
        this.formData?.forEach((item) => {
            item?.data?.map((child) => {
                console.log(child,1111111)
                // 回显的第3个条件,现在是不可编辑
                child.status3 = true
            });
        });
        console.log(this.formData)
        // this.formData = cache.value ? JSON.parse(cache.value) : [{
        //   title: '条件', id: '1', data: [
        //     {
        //       id: new Date().getTime(),
        //       name: '条件',
        //       type: '',
        //       type1: '',
        //       type2: '',
        //       condition: '',
        //       value: '',
        //       input: '=',
        //       inputValue: '',
        //       state1: true,
        //       state2: true,
        //     }
        //   ]
        // }]
        this.formInfo = cache;
    },
    methods: {
        deleteItem(item, index) {
            item.splice(index, 1);
        },
        // 获取表单列表
        getFormList() {
            getFormDate({
                bizType: this.$route.query.category,
            }).then((res) => {
                if (res.data.length > 0) {
                    let obj = [];
                    res.data.map((item) => {
                        if (item.flowBusFieldList?.length > 0) {
                            // obj = obj.push(...item.flowBusFieldList);
                            obj = obj.concat(item.flowBusFieldList);
                        }
                    });
                    this.typeOptions = obj;
                }
            });
        },
        // 条件节点-第一个下拉框
        firstChange(value, info, data) {
            let item = this.typeOptions.find((e) => e.fieldKey == value);
            let fieldType = "";
            if (item) {
                fieldType = item.fieldType;
            }
            this.$set(info, "fieldType", fieldType);
            if (fieldType == "1") {
                this.$set(info, "value2", "");
                this.$set(info, "value3", "");
            } else if (fieldType == "2") {
                this.$set(info, "fieldDict", item?.fieldDict);
                this.$set(info, "value2_disabled", true);
                this.$set(info, "value2", "==");
                this.$set(info, "value3", "");
            } else if (fieldType == "3") {
                this.$set(info, "fieldDict", item?.fieldDict);
                this.$set(info, "value2_disabled", true);
                this.$set(info, "value2", "==");
                this.$set(info, "value3", "");

                // this.formData.map((res) => {
                //     if (data.id == res.id) {
                //         res.data.map((item) => {
                //             if (item.id == info.id) {
                //                 item.state1 = false;
                //             }
                //         });
                //     }
                // });
            } else {
                this.$set(info, "value2_disabled", false);
                this.$set(info, "value2", "");
                this.$set(info, "value3", "");
            }
            this.initOpitions(info);
        },
        initOpitions(info) {
            if (info.fieldType == "1") {
                this.$set(info, "value2_disabled", false);
                this.$set(info, "typeOptions2", [
                    {
                        dictLabel: ">",
                        dictValue: ">",
                    },
                    {
                        dictLabel: ">=",
                        dictValue: ">=",
                    },
                    {
                        dictLabel: "=",
                        dictValue: "==",
                    },
                    {
                        dictLabel: "<",
                        dictValue: "<",
                    },
                    {
                        dictLabel: "<=",
                        dictValue: "<=",
                    },
                ]);
            } else if (info.fieldType == "2") {
                // let item = this.typeOptions?.find(
                //     (e) => e.fieldType == info.fieldType
                // );

                this.$set(info, "value2_disabled", true);
                this.$set(info, "value2", "==");

                this.$set(info, "typeOptions2", [
                    {
                        dictLabel: "==",
                        dictValue: "==",
                    },
                ]);
                if (info?.fieldDict) {
                    this.getDicts(info?.fieldDict)
                        .then((response) => {
                            this.$set(info, "typeOptions3", response.data);
                        })
                        .catch(() => {
                            this.$set(info, "typeOptions3", []);
                        });
                }
            } else if (info.fieldType == "3") {
                this.$set(info, "value2_disabled", true);
                this.$set(info, "value2", "==");
                this.$set(info, "typeOptions2", [
                    {
                        dictLabel: "==",
                        dictValue: "==",
                    },
                ]);

                getLessorList(info.fieldDict,info.fieldDict?.indexOf("creditReview")>-1?"post":"get").then((res)=>{
                    console.log(res,11111111)
                    if(res.code==200){
                        this.$set(
                            info,
                            "typeOptions3",
                            this._.cloneDeep(res.data)
                        );
                    }

                })

            } else {
                this.$set(info, "value2_disabled", false);
                this.$set(info, "typeOptions2", []);
                this.$set(info, "typeOptions3", []);
            }
        },
        getApproveList(info) {
            return new Promise((resolve) => {
                ApproveList({})
                    .then((res) => {
                        if (res.code == 200) {
                            // this.$set(info, "typeOptions3", res.data);
                            this.typeOptions3List = res.data;
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    })
                    .finally(() => {
                        resolve();
                    });
            });
        },
        // 条件节点-第二个下拉框
        secendChange(value, info, data) { },
        // 条件节点-第三个下拉框
        seardChange(value, info, data) { },
        // 添加字段
        addField(info) {
            this.formData.map((res) => {
                if (res.id == info.id) {
                    let obj = {
                        name: "条件",
                        id: res.data.length + 1,
                        type: "",
                        condition: "",
                        value: "",
                        input: "=",
                        inputValue: "",
                        state1: true,
                        state2: true,
                    };
                    res.data.push(obj);
                }
            });
        },
        // 添加条件
        addCondition() {
            let obj = {
                title: "条件",
                id: this.formData.length + 1,
                data: [
                    {
                        name: "条件",
                        id: new Date().getTime(),
                        type: "",
                        condition: "",
                        value: "",
                        input: "=",
                        inputValue: "",
                        state1: true,
                        state2: true,
                    },
                ],
            };
            this.formData.push(obj);
        },
    },
};
</script>

<style lang="scss" scoped>
::v-deep .el-input-number {

    // width: 220px;
    input {
        width: 100%;
        text-align: left;
        padding: 0 5px !important;
    }

    .el-input-number__decrease {
        display: none;
    }

    .el-input-number__increase {
        display: none;
    }
}

.itemTitle {
    display: flex;
    align-items: center;

    i {
        margin-left: 5px;
    }
}

.formItem {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.delete {
    cursor: pointer;
    color: red;
}
</style>
